<template>
  <div class="layout-container">
    <div class="layout-container-form" style="flex-direction: column">
      <div class="layout-container-form-search">
        <el-row style="text-align: left">
          <el-col :span="24">
            <el-form label-width="90px" :inline="true">
              <el-form-item label="团长姓名：">
                <el-input v-model="query.user_name" placeholder="请输入姓名" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="团队编号：">
                <el-input v-model="query.team_number" placeholder="请输入团队编号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label-width="140px"  label="本月有效邀请人数：">
                <el-input v-model="query.team_people" placeholder="请输入人数" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
               <el-form-item label="状态：">
                <el-select v-model="query.status" placeholder="请选择状态" style="width: 100%" clearable @clear="clearStatus"
                  @change="changeStatus">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
             <el-form-item label="用户ID：">
                <el-input v-model="query.user_id" placeholder="请输入用户ID" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
            <el-form-item label="团队等级：">
                <el-input v-model="query.level" placeholder="请输入团队等级" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="团队本月总收入：">
                <el-input v-model="query.team_income" placeholder="请输入团队本月总收入" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="历史人数：">
                <el-input v-model="query.team_people_history" placeholder="请输历史人数" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="search-btn" style="margin-left: 8px" @click="resetSearch">{{
                    $t("message.common.reset")
                }}</el-button>
                <el-button type="primary" class="search-btn" @click="getTableData(true)">{{ $t("message.common.search")
                }}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="layout-container-opt" style="">
         <div style="padding:0 20px 0 20px">
            <el-checkbox v-model="checkAll" label="1" @change="changeAll">全选</el-checkbox>
        </div>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'" 
          :loading="exportBatchLoading" @click="handleBatchImport(1)">
          批量新增团队
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'"
          :loading="exportBatchLoading" @click="handleBatchImport(2)">
          批量修改团队信息
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'"
          :loading="exportBatchLoading" @click="handleBatchImport(4)">
          批量修改团队历史等级
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'"
          :loading="exportBatchLoading" @click="handleBatchImport(3)">
          批量修改团员信息
        </el-button>
         <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="selectData.length > 0 ? 'primary' : ''" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="exportExcelFun">
          批量导出团队数据
        </el-button>
        <el-button class="search-btn" icon="el-icon-refresh-right" style="position:absolute;right:0;bottom:8px;"
          @click="getTableData(true)">{{ $t("message.common.refresh") }}</el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true"
       :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
            <el-table-column 
            v-for="(item,index) in columns" :type="item.type" :key="index"
            :label="item.label"
            :width="item.width"
            :property="item.property">
                <template #default="scope" v-if="item.input">
                    <el-input v-model="scope.row.dict_number" placeholder="" />
                </template>
                <template #default="scope" v-else-if="item.copy">
                    <span>{{scope.row[item.property]}} 
                        <el-icon class="cup" v-copy="scope.row[item.property]"  color="#409eff"><DocumentCopy /></el-icon>
                    </span>
                </template>
                <template #default="scope" v-else-if="item.tooltip">
                    <el-popover
                        placement="bottom"
                        width="300"
                        @show="(()=>{getHistoryPeopleLevel(scope.row)})"
                        :disabled="item.property == 'team_permissions' && scope.row[item.property] ==''?true:false"
                        trigger="hover">
                        <div slot="content">
                            <template v-if="item.property == 'team_people_level'">
                                <div v-for="(el, i) in historyPeopleLevelArr" :key="i">
                                    {{el.replace(',','，')}}
                                </div>
                            </template>
                            <template v-if="item.property == 'team_permissions'">
                                {{scope.row[item.property]}}
                            </template>
                            
                        </div>
                        <template #reference>
                             <template v-if="item.property == 'team_permissions'">
                                <span v-if="scope.row[item.property] == ''">所有项目</span>
                                <el-button v-else type="text">详情</el-button>
                            </template>
                            <el-button v-else type="text">{{scope.row[item.property]}}</el-button>
                        </template>
                    </el-popover>
                </template>
                <template  #default="scope" v-else>
                    <template v-if="item.property">
                        <el-input
                            v-if="scope.row.showInput" 
                            v-model="scope.row[item.property]" 
                            placeholder="" />
                        <span v-else>{{scope.row[item.property]}}</span>
                    </template>
                </template>
                
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="text" v-if="!scope.row.showInput" @click="handleOpt(scope.row,1,scope.$index)">详情</el-button>
                    <el-button type="text" v-if="scope.row.status == 0" @click="handleOpt(scope.row,2,scope.$index)">入职</el-button>
                    <el-button type="text" v-if="scope.row.status == 1" @click="handleOpt(scope.row,3,scope.$index)">离职</el-button>
                    <el-button type="text" v-if="!scope.row.showInput" @click="handleOpt(scope.row,4,scope.$index)">合并删除</el-button>
                    
                </template>
            </el-table-column>
      </Table>
    </div>
      <!-- 上传文件弹出框组件 -->
        <BatchImportDialog 
        v-if="uploadObj.visible"
        :visible="uploadObj.visible"
        :title="uploadObj.title"
        :uploadObj="uploadObj"
        @closeUploadDialog="closeUploadDialog"
        @refreshTable="refreshTable"/>
  </div>
</template>

<script lang="ts">
import { defineComponent} from "vue";
import Copy from '@/directive/copy'
  export default defineComponent({
    directives: {
      Copy
    },
  
    setup(props) {
    }
  })
</script>
<script setup lang="ts">
import {  ref, reactive } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox ,ElIcon } from "element-plus";
import {
  DocumentCopy
} from '@element-plus/icons-vue'

import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import Table from "@/components/table/index.vue";
import {
  teamPage,historyPeopleLevel,teamEdit,inviteUrl,teamInfoExport,deleteTeam
} from "@/api/team.ts";
import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ossPrefixNew } from "@/utils/index.ts";


const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  user_name: '', // string
  team_number: '', // string
  status: -1, // string
//   user_get_date_time: [], // array[string]
  user_id: '', // string
  level: '', // string
  team_income: '', // string
  team_people_history: '', // string
  team_people: '', // string
});
// 状态 0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废
const statusOptions = ref([
   {
    label: '全部',
    value: -1
  },
  {
    label: '已离职',
    value: 0
  },
  {
    label: '任职中',
    value: 1
  },
])
// 清空状态
const clearStatus = () => {
  query.status = undefined;
  getTableData(true);
}
// 状态change事件
const changeStatus = () => {
  getTableData(true);
}
// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
    query.user_name = ''//
    query.team_number = ''//, // string
    query.status = -1//, // string
    //   user_get_date_time: [], // array[string]
    query.user_id = ''//, // string
    query.level = ''//, // string
    query.team_income = ''//, // string
    query.team_people_history = ''// // string
    query.team_people = ''//, // string
    query.status = -1
    // query.status = undefined, // integer -1: 查所有
    // query.team_number = '', // string
    // query.user_get_date_time = [], // string
    // query.user_id = '', // string
    
    getTableData(true);
}

const columns = reactive([
    {
        label:'序号',
        property:'Id', 
        width:'55',
    },
    {
        label:'团长ID',
        property:'user_id',
    },{
        label:'团长姓名',
        property:'user_name',
    },{
        label:'昵称',
        property:'nick_name',
    },{
        label:'团长手机号',
        property:'tl_phone',
    },{
        label:'团长邮箱',
        property:'tl_email',
    },{
        label:'团队编号',
        property:'team_number',
    },{
        label:'团队本月等级',
        property:'level',
    },{
        label:'本月邀请进度',
        property:'now_invite_progress',
    },{
        label:'当前月份',
        property:'now_month',
    },{
        label:'上月团队等级',
        property:'last_month_level',
    },{
        label:'历史月份有效人数与等级',
        property:'team_people_level',
        tooltip:true,
    },{
        label:'历史总有效人数',
        property:'team_people_history',
    },{
        label:'团长专属链接',
        property:'team_user_url',
        copy:true,
    },{
        label:'团队本月总收入芝草',
        property:'team_income',
    },{
        label:'任职状态',
        property:'statusName',
    },{
        label:'团队项目可见配置',
        property:'team_permissions',
        tooltip:true,
    }
]);


const loading = ref(false);
const tableData = ref([]);



const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
      if(selectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
      selectData.value = [];
      table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
 selectData.value = [];
  if(data.length){
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectData.value.push(item.Id);
    });
  }
};
const getParams = () =>{
  query.team_people_history = query.team_people_history?query.team_people_history*1:''
  query.team_people = query.team_people?query.team_people*1:''
  return {
      page: page.index,
      page_size: page.size,
      ...query,
      status: query.status === undefined ? -1 : query.status +'', // integer -1: 查所有
    }
}
// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
  let params = {
    ...getParams()
    // u_team_number: query.team_number, // string
    // user_get_date_time: query.user_get_date_time ? query.user_get_date_time : [], // string
    // user_id: query.user_id, // string
  };
  Object.keys(params).map(item => {
    if(params[item] == ''){
        delete params[item]
    }
  })
  if(params.status == -1){
    delete params.status
  }
  teamPage(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
        d.team_user_url = inviteUrls.value + d.team_number
        d.statusName = d.status == 0?'已离职':'任职中'
        d.team_people_level = '详情'

        if(d.now_invite_progress == ''){
          d.now_invite_progress = d.team_people +'/'+d.now_invite_progress_new
        }
      });

      tableData.value = data;
      page.total = Number(res.data.count);
      if(checkAll.value){
          changeAll(true)
      }else{
        changeAll(false)
      }
      
      console.log(tableData.value)
    })
    .catch(() => {
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
const replaceStr =  (str, index, char) => {
    const strAry = str.split('');
    strAry[index] = char;
    return strAry.join('');
}
const tooltipType = ref('')
const historyPeopleLevelArr = ref([]);
const getHistoryPeopleLevel = (row:any)=>{
    historyPeopleLevel({id:row.Id}).then(res => {
        if(res.code == 200){
          let arr = [],str = ''
          res.data.list = res.data.list.map(item => {
            arr = item.split(':')
            if(arr[0].substr(5,1)== 0){
              arr[0] = replaceStr(arr[0],5,'')
            }
            item = arr.join(':')
            return item
          })
            historyPeopleLevelArr.value =res.data.list 
        }else{
            ElMessage.success(res.message);
        }
    })
}
const inviteUrls = ref('')
const getInviteUrl = ()=>{
    inviteUrl({}).then(res => {
        if(res.code == 200){
          getTableData(true)
          inviteUrls.value = res.data.dict_value
        }else{
            ElMessage.success(res.message);
        }
    })
}
getInviteUrl()
// 操作
const handleOpt = (row: any, type: Number,index:Number) => {
  if(type == 1){
      router.push({
        path:'/backstagerpzzm/teamManage/teamDetail',
        query:{user_id:row.user_id}
      })
      return
  }
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 详情
      let par = {
        id:row.Id,
      }
     if(type == 2){// 入职
        par.status = 1;
        
      }else if(type == 3){// 离职
         par.status = 0;
      }else if(type == 4){// 删除
        par.teamNumber = row.team_number
        delete par.id
        deleteTeamFunc(par)
        return 
      }
      setProfileUdate(par,row,index)
    })
    .catch(() => { });
};

const setProfileUdate = (par:any,row:Object,index:Number)=> {
    teamEdit(par).then(res => {
        if(res.code == 200){
            debugger
            ElMessage.success('操作成功！');
            tableData.value.splice(index,1,{...row,status:par.status})
        }else{index
           ElMessage.success(res.message);
        }
    })
}

const deleteTeamFunc = (par:any)=> {
    deleteTeam(par).then(res => {
        if(res.code == 200){
            ElMessage.success('操作成功！');
            getTableData(false)
        }else{index
           ElMessage.success(res.message);
        }
    })
}

// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost(selectData.value)
}
// 导出通用函数
const exportExcelPost = (ids: any) => {
  let data = {
      ...getParams(),
    ids: [], // array[interger]
    // project_ids: project_ids, // array[string]
  }
  delete data.page
  delete data.page_size

   data.ids = ids.map(item =>{return item })
  // if(checkAll.value){
  // }else{
  //   if(ids){
  //     data.ids = ids.map(item =>{return item })
  //   }
  // }
  teamInfoExport(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}



// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
}
const refreshTable = ()=>{
    ElMessage.success("导入成功！")
    closeUploadDialog()
    getTableData(true)
}

const handleBatchImport = (type:any) => {
  let obj = {
    1:{
      title:'批量上传团队',
      name:'新团队开通表',
      url:'/admin/team/team_import',
    },
    2:{
      title:'批量修改团队',
      name:'团队信息变更表',
      url:'/admin/team/team_import_update',
    },
    3:{
      title:'批量修改团员信息',
      name:'团员信息变更表',
      url:'/admin/team/team_update_user_import',
    },
    4:{
      title:'批量修改团队历史等级',
      name:'团队历史等级',
      url:'/admin/team/team_import_update_history_level',
    }
  } 
  uploadObj.visible = true;
  uploadObj.title =  obj[type].title;
  uploadObj.url =  obj[type].url;
  uploadObj.downloadObj.name =  obj[type].name; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}${obj[type].name}.xlsx`; // excel模板下载地址
}


</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}

.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.cup{
    cursor: pointer;
}
</style>
